<!-- 
<template>
  <div id="list">
    <p> 商品列表</p>
    <div>
      <div class="list-data">
        <div class="product-name"> 商品名称 </div>
        <div> 所属分类 </div>
        <div> 商品价值 </div>
        <div> 商品图片 </div>
        <div class="product-describe"> 商品描述 </div>
        <div class="product-operation"> 操作 </div>
      </div>
      <div class="list-data" v-for="(item) in commodityData.commodityList" :key="item.id">
        <div class="product-name">{{ item.ProductName }}</div>
        <div>{{ item.category }}</div>
        <div>{{ item.commodityValue }}</div>
        <div> <img :src="item.ProductPicture" alt="图片加载失败" class="product-image"></div>
        <div class="product-describe">{{ item.ProductDescription }}</div>
        <div class="product-operation">
          <button @click="showEditDialog(item)">编辑</button>
          <button @click="confirmDelete(item.id)">删除</button>
        </div>
      </div>
    </div>

    
    <div v-if="editDialogVisible" class="edit-dialog">
      <div class="dialog-content">
        <div>
          <label>商品名称:</label>
          <input v-model="currentProduct.ProductName" />
        </div>
        <div>
          <label>所属分类:</label>
          <input v-model="currentProduct.category" />
        </div>
        <div>
          <label>商品价值:</label>
          <input v-model="currentProduct.commodityValue" />
        </div>
        <div>
          <label>商品描述:</label>
          <textarea v-model="currentProduct.ProductDescription"></textarea>
        </div>
        <div>
          <label>商品图片:</label>
          <input v-model="currentProduct.ProductPicture" />
        </div>

        <div class="dialog-buttons">
          <button @click="saveEdit">确定</button>
          <button @click="closeEditDialog">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import {  } from '../../api/goods';

const commodityData = ref({
  commodityList: [
    { id: 1, ProductName: '素什锦单人冒菜(赠米饭)', category: '(冒菜)套餐自选区', commodityValue: 15.00, ProductPicture: '01.png', ProductDescription: '素什锦单人冒菜(赠米饭)主要原料:水' },
    { id: 2, ProductName: '荤素单人冒菜(赠米饭+饮品)', category: '(冒菜)套餐自选区', commodityValue: 19.00, ProductPicture: '02.png', ProductDescription: '荤素单人百菜(赠米饭+饮品)主要原料:其他' },
    { id: 3, ProductName: '青椒猪肉串', category: '撸烤串', commodityValue: 4.9, ProductPicture: '03.png', ProductDescription: '香辣椒香入味，满足味蕾 主要原料:猪肉' },
    { id: 4, ProductName: '泡椒牛肉丝双拼+香菇鸡双拼+赠饮品', category: '满减专区', commodityValue: 60, ProductPicture: '04.png', ProductDescription: '超级豪华双人餐，饮品随机。主要原料:牛肉,鸡肉' },
  ]
});

const editDialogVisible = ref(false);
const currentProduct = ref({});

function showEditDialog(product) {
  currentProduct.value = { ...product }; // 创建产品副本以避免直接修改原数据
  editDialogVisible.value = true;
}

function closeEditDialog() {
  editDialogVisible.value = false;
}

function saveEdit() {
  const index = commodityData.value.commodityList.findIndex(item => item.id === currentProduct.value.id);
  if (index !== -1) {
    commodityData.value.commodityList[index] = { ...currentProduct.value };
  }
  editDialogVisible.value = false;
}

function confirmDelete(id) {
  if (confirm('您确定要删除这个商品吗？')) {
    viewData(id);
  }
}

function viewData(id) {
  commodityData.value.commodityList = commodityData.value.commodityList.filter(item => item.id !== id);
}
</script>

<style lang="scss" scoped>
.list-data {
  display: flex;
  align-items: center; // 确保图片和其他文本垂直居中对齐

  div {
    flex: 1;
    height: 60px;
    padding: 10px;
    border: 1px solid #eee;
  }

  .product-name {
    flex: 3;
  }

  .product-describe {
    flex: 3;
  }

  .product-operation {
    flex: 2;
  }

  .product-image {
    max-width: 100px; // 设置图片最大宽度
    height: auto; // 保持图片比例
  }
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;

  .dialog-content {
    background: white;
    padding: 30px;
    border-radius: 12px;
    width: 50%; // 调整弹框宽度
    max-width: 600px; // 最大宽度限制

    div {
      margin-bottom: 15px;
    }

    label {
      display: block;
      margin-bottom: 5px;
    }

    input,
    textarea {
      width: 100%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    textarea {
      height: 100px;
    }

    .dialog-buttons {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;

      button {
        margin-left: 10px;
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }

      button:first-child {
        background-color: #4CAF50;
        color: white;
      }

      button:last-child {
        background-color: #f44336;
        color: white;
      }
    }
  }
}
</style> -->
<template>
  <div id="ListView">
    <div class="box">
      <div class="box_header">商品列表</div>
      <!-- 商品列表 -->
      <el-table :data="currentOrders" style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div m="4">
              <p m="t-0 b-2">商品ID: {{ props.row.id }}</p>
              <p m="t-0 b-2" class="pNow">所属分类: {{ props.row.category }}</p>
              <p m="t-0 b-2">创建时间: {{ props.row.ctime }}</p>
              <p m="t-0 b-2">商品销量: {{ props.row.rating }}</p>
              <p m="t-0 b-2">商品图片: <br><img :src="'http://127.0.0.1:5000/upload/imgs/goods_img/' + props.row.imgUrl"
                  alt=""></p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name" />
        <el-table-column label="所属分类" prop="category" width="200" />
        <el-table-column label="商品价格" prop="price" width="150">
          <template #default="scoped">
            ￥{{ scoped.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" prop="imgUrl" width="150">
          <template #default="scoped">
            <img :src="'http://127.0.0.1:5000/upload/imgs/goods_img/' + scoped.row.imgUrl" alt="">
          </template>
        </el-table-column>
        <el-table-column label="商品描述" prop="goodsDesc" width="500" />
        <el-table-column label="操作" width="180">
          <template #default="scoped">
            <el-button type="primary" @click="handleEdit(scoped.row.id)">编辑</el-button>
            <el-button @click="open(scoped.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!--翻页-->
      <div class="pageBox">
        <div class="demo-pagination-block">
          <!-- <div class="demonstration">All combined</div> -->
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5]" :size="size"
            layout="total, sizes, prev, pager, next, jumper" :total="tableList.length" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" class="pageBox_use" />
        </div>
      </div>
      <!-- 商品编辑 -->
      <div class="goods_edit" v-show="msg">
        <div class="title">
          <div>编辑商品</div>
          <div class="close" @click="close">X</div>
        </div>
        <div class="goods_body">
          <span>商品名称</span>
          &nbsp;
          <input type="text" v-model="goodsName">
        </div>
        <div class="goods_body">
          <span>所属分类</span>
          &nbsp;
          <input type="text" v-model="goodsClass">
        </div>
        <div class="goods_body">
          <span>商品价格</span>
          &nbsp;
          <input type="text" v-model="goodsPrice">
        </div>
        <div class="goods_body">
          <span>商品描述</span>
          &nbsp;
          <input type="text" v-model="goodsWord">
        </div>
        <div class="goods_body">
          <span>商品图片</span>
          <br><br>
          <img :src="goodsImg" alt="">
        </div>
        <div class="goods_bottom">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleGoodsEdit">确定</el-button>
        </div>
      </div>
    </div>
    <!-- 蒙版 -->
    <div class="mask" v-show="msg"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { fetchLoginFive, fetchLoginSix, fetchLoginSeven } from '../../api/index';
import { ComponentSize } from 'element-plus';

//商品编辑
const msg = ref(false);
const goodsName = ref('');
const goodsClass = ref('');
const goodsPrice = ref('');
const goodsWord = ref('');
const goodsImg = ref('');
const goodsId = ref('');
//传参修改商品用图片路径
const goodsImgEdit = ref('');
interface GoodsItem {
  id: number;
  name: string;
  category: string;
  price: any;
  goodsDesc: string;
  imgUrl: string;
}
const tableList = ref<GoodsItem[]>([]);


function handleEdit(id: any) {
  msg.value = !msg.value;
  console.log(id);
  const index = tableList.value.findIndex((item) => item.id === id);
  goodsId.value = id;
  goodsName.value = tableList.value[index].name;
  goodsClass.value = tableList.value[index].category;
  goodsPrice.value = tableList.value[index].price;
  goodsWord.value = tableList.value[index].goodsDesc;
  goodsImg.value = 'http://127.0.0.1:5000/upload/imgs/goods_img/' + tableList.value[index].imgUrl;
  goodsImgEdit.value = tableList.value[index].imgUrl;
}

function close() {
  msg.value = !msg.value;
}

const handleGoodsEdit = async () => {
  msg.value = !msg.value;
  interface IUserInfo {
    name: string,
    category: string,
    price: string,
    imgUrl: string,
    goodsDesc: string,
    id: string,
  }

  const userInfo = ref<IUserInfo>({
    name: goodsName.value,
    category: goodsClass.value,
    price: goodsPrice.value,
    imgUrl: goodsImgEdit.value,
    goodsDesc: goodsWord.value,
    id: goodsId.value,
  })

  const res = await fetchLoginSeven(userInfo.value);
  console.log(res);

}

//引入弹框类型
import { ElMessage, ElMessageBox } from 'element-plus'
//引入删除弹框以及删除操作
const open = (id: any) => {
  ElMessageBox.confirm(
    '是否删除该商品?',
    '警告',
    {
      confirmButtonText: '是的',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //console.log(id);
      //const index = tableList.value.findIndex((item) => item.id === id)
      //console.log(index);
      const userInfo = ref({
        id: id,
      })
      const res = await fetchLoginSix(userInfo.value);
      console.log(res);//删除成功
      location.reload();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//日期转换
function formatDateTime(dateTimeStr: any) {
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');

  //
  const offsetHours = 8; // UTC+8
  const localHours = date.getUTCHours() + offsetHours;
  return `${year}-${month}-${day} ${localHours}:${minutes}:${seconds}`;
}

//获取商品列表数据
onMounted(async () => {
  const res = await fetchLoginFive({ currentPage: 1, pageSize: 80 });
  console.log(res.data.data);
  const data = res.data.data.map((item: any) => {
    //字段是ctime
    if (item.ctime) {
      item.ctime = formatDateTime(item.ctime);
    }
    return item;
  });
  tableList.value = data;
})

//翻页联动列表
const currentPage = ref(1)
const pageSize = ref(5)
const size = ref<ComponentSize>('default')

//表格数据绑定翻页
const currentOrders = computed(() => {
  return tableList.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

//数组列表数据
// const tableList = ref([]);
</script>

<style scoped>
.box {
  /* width: 85vw; */
  margin: 10px;
  box-shadow: 0.1vw 0.1vw 0.1vw 0.1vw #f0f0f0;
}

.box_header {
  padding: 1vw;
  border-bottom: 1px solid #f0f0f0;
}

.pageBox {
  height: 5vh;
}

.pageBox_use {
  margin-top: 1vh;
  margin-left: 1vw
}

.goods_edit {
  width: 35vw;
  height: 25vw;
  padding: 2vw;
  position: absolute;
  top: 10vw;
  left: 35vw;
  z-index: 9999;
  background-color: #fff;

  .goods_body {
    width: 30vw;
    height: 3vw;
    font-size: 0.8vw;

    input {
      width: 25vw;
      height: 2vw;
      font-size: 0.8vw;
      border: 0.1vw solid #f0f0f0;
      outline: none;
    }
  }

  .goods_bottom {
    height: 3vw;
    margin-top: 6vw;
    display: flex;
    justify-content: right;
  }
}

.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 8888;
  background-color: rgb(0, 0, 0, 0.5);
}

img {
  width: 5vw;
  height: 5vw;
}

.title {
  height: 3vw;
  font-size: 1.2vw;
  display: flex;
  justify-content: space-between;

  .close {
    cursor: pointer;
  }
}
</style>